using System;
using System.Collections.Generic;
using UnityEngine;


public class CardLayoutManager : MonoBehaviour
{
   [Header("是否水平布局")] public bool isHorizontal;

   [Header("最大宽度")] public float maxWidth = 7f;

   [Header("卡牌间距")] public float cardSpacing = 2f;

   [Header("卡牌位置")] public Vector3 centerPoint;
   [Header("弧形参数")] public float angleBetweenCards = 7f;
   public float radius = 17f;

   //卡牌位置列表
   private List<Vector3> cardPosition = new();

   //卡牌旋转列表
   private List<Quaternion> cardRotation = new();

   private void Awake()
   {
      centerPoint = isHorizontal ? Vector3.up * -5f : Vector3.up * -21.5f;
   }

   public CardTransform GetCardTransform(int index, int totalCards)
   {
      CalculateCardPosition(totalCards, isHorizontal);
      return new CardTransform(cardPosition[index], cardRotation[index]);
   }


   private void CalculateCardPosition(int numberOfCards, bool horizontal)
   {
      cardPosition.Clear();
      cardRotation.Clear();
      if (horizontal)
      {
         float currentWidth = cardSpacing * (numberOfCards - 1);
         float totalWidth = Mathf.Min(maxWidth, currentWidth);

         float currentSpacing = totalWidth > 0 ? totalWidth / (numberOfCards - 1) : 0;

         for (int i = 0; i < numberOfCards; i++)
         {
            float xPos = 0 - (totalWidth / 2) + (i * currentSpacing);

            var pos = new Vector3(xPos, centerPoint.y);
            var rot = Quaternion.identity;
            cardPosition.Add(pos);
            cardRotation.Add(rot);
         }
      }
      else
      {
         float currentWidth = cardSpacing * (numberOfCards - 1);
         float totalWidth = Mathf.Min(maxWidth, currentWidth);
         
         float currentSpacing = totalWidth > 0 ? totalWidth / (numberOfCards - 1) : 0;
         
         float cardAngle = (numberOfCards - 1) * angleBetweenCards / 2;

         for (int i = 0; i < numberOfCards; i++)
         {
            var pos = FanCardPosition(cardAngle - i * angleBetweenCards);

            // var newPos = new Vector3(pos.x - (totalWidth / 2) + (i * currentSpacing), pos.y, pos.z);

            var rotation = Quaternion.Euler(0, 0, cardAngle - i * angleBetweenCards);
            cardPosition.Add(pos);
            cardRotation.Add(rotation);
         }
      }
   }

   private Vector3 FanCardPosition(float angle)
   {
      return new Vector3(
         //Mathf.Deg2Rad弧度转角度
         centerPoint.x - Mathf.Sin(Mathf.Deg2Rad * angle) * radius,
         centerPoint.y + Mathf.Cos(Mathf.Deg2Rad * angle) * radius,
         0
      );
   }
}
